<template>
  <el-dialog
    title="发送邮件"
    :visible.sync="show"
    width="70%"
    center
    @close="handleClose"
    :close-on-click-modal="false"
    custom-class="sendEmialDialog"
  >
    <div>
      <el-form label-width="80px" :model="emailContent" ref="form" :rules="rules" >
        <el-form-item label="邮件标题" prop="title">
          <el-input v-model="emailContent.title"></el-input>
        </el-form-item>
        <el-form-item label="邮件内容" prop="mailbody">
          <wangEidtor ref="edit" @change="handelKeyDown(true, $event)" :editId="'sendEmail'" />
        </el-form-item>
      </el-form>
    </div>
    <p>学生列表 ({{studentList.length || 0}}人)</p>
    <div style="padding-left: 40px;margin-top:10px;">
      <!-- <div class="stuList">
        <el-tooltip class="item" effect="dark" :content="item.stuNum ||'无学号'" placement="top-start" v-for="(item, index) in studentList" :key="index">
          <span class="stuLabel" >{{item | filterUserName}}</span>
        </el-tooltip>
      </div> -->
        <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入用户信息"
          v-model="selectStuList"
          :titles="['未选学生', '已选学生']"
          :button-texts="['取消', '选择']"
          :data="mapStudentList"
          :props="{
            key: 'userID',
            label: 'name'
          }"
          >
        </el-transfer>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="handelConfirm" :disabled="!selectStuList.length">发送</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { debounce } from "@/util/tool";
import { sendEmailByUserID } from "@/request/teacher";
const wangEidtor = () => import("@/components/wangEditor/index.vue");
export default {
  components: {
    wangEidtor,
  },
  data() {
    let validateMailBody = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入邮件内容"));
      } else {
        callback();
      }
    };
    return {
      show: false,
      emailContent: {
        title: "",
        mailbody: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入邮件标题", trigger: "blur" },
        ],
        mailbody: [
          { required: true, message: "请输入邮件内容", trigger: "blur" },
          { validator: validateMailBody, trigger: "blur" },
        ],
      },
      isInit: true,
      // data: generateData(),
      selectStuList: [],
      filterMethod(query, item) {
        return query == '' || (query && item?.name && `${item?.name}`?.indexOf(query) !== -1) ||item?.name == query;
      }
    };
  },
  props: {
    isShowDialog: Boolean,
    studentList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  watch: {
    isShowDialog(n) {
      this.show = n;
    },
  },
  computed: {
    mapStudentList() {
      let data = this.studentList.map(item => {
        item.name = `${this.getUserInfo_name(item)}`
        return item
      })
      return data
    }
  },
  filters: {
    filterUserName(value) {
      return value ? (
        value.realName ||
        value.nickName ||
        value.email ||
        value.regName ||
        value.stuNum ||
        value.userID
      ) : '无信息';
    },
  },
  created() {
    if (this.isShowDialog) this.show = this.isShowDialog;
  },
  methods: {
    handleClose() {
      this.$emit("close");
    },
    getUserInfo_name(value) {
      return value ? (
        value.realName ||
        value.nickName ||
        value.email ||
        value.regName ||
        value.stuNum ||
        value.userID
      ) : '无信息';
    },
    handelKeyDown: debounce(
      function (immediate, data) {
        this.emailContent.mailbody = data.data
        if (data.data) {
          this.$refs["form"].clearValidate("mailbody")
        } else {
          if (this.isInit) return
          this.$refs['form'].validateField(['mailbody'])
        }
        this.isInit = false
      },
      0,
      false
    ),
    // 清空富文本编辑器的内容
    confirm() {
      this.$emit("confirm", this.content);
      this.$refs.edit.editor.txt.clear();
    },
    // 提交 检查表单
    handelConfirm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 信息校验成功
          this.sendEmail()
        } else {
          // 信息校验不通过
          return false;
        }
      });
    },
    sendEmail() {
      const params = {
        userIDArray: this.selectStuList,
        mailbody: this.emailContent.mailbody,
        title: this.emailContent.title
      }
      sendEmailByUserID(params).then(res=> {
        if(res.errno == 0) {
          this.show = false
          this.handleClose()
          this.$antdMessage.success({content: "发送成功"})
        } else {
          this.$antdMessage.error({content: res.message || "发送失败"})
        }
      })
    }
  },
};
</script>

<style lang="stylus">
.sendEmialDialog {
  .wangEditor {
    .w-e-text-container {
      height: 300px;
      max-height: 4000px;
    }
  }

  .stuList {
    margin-left: 20px;
    padding-top: 10px;
    padding-bottom: 20px;
    max-height: 180px;
    overflow: auto;
    overflow-x: hidden;

    .stuLabel {
      margin-bottom: 10px;
      margin-right: 10px;
      display: inline-block;
      // padding: 0 15px;
      width 85px;
      text-align: center;
      background-color: #b6b9e2;
      border-radius: 40px;
      color: #000
      font-family: Source Han Sans CN;
      font-size: 0.9rem;
    }
  }
}
</style>